package org.gruposp2p.openid.provider

import java.util.Collection;
import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUser
import java.util.ArrayList;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.codehaus.groovy.grails.plugins.springsecurity.GormUserDetailsService;
import org.codehaus.groovy.grails.commons.ConfigurationHolder
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
import javax.servlet.http.HttpSession
import org.gruposp2p.openid.provider.OpenIdUser;

class OpenIdUserDetailsService extends GormUserDetailsService {

	@Override
	public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
		ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
		HttpSession httpSession = attr.getRequest().getSession(true);
		log.debug "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
		log.debug "@@@@@@@@@@@@@@ - username: " + username
		log.debug "@@@@@@@@@@@@@@ - userClaimedId: " + httpSession.getAttribute('userClaimedId')
		log.debug "@@@@@@@@@@@@@@ - amount: " + httpSession.getAttribute('amount')
		log.debug "@@@@@@@@@@@@@@ - to: " + httpSession.getAttribute('to')
		log.debug "@@@@@@@@@@@@@@ - memo: " + httpSession.getAttribute('memo')
		def user
		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		UserDNI.withTransaction {
			if (ConfigurationHolder.config.grails.plugins.springsecurity.useX509) {
				log.debug "@@@@@@@@@@@@@@ - findByNif: " + username
				user = UserDNI.findByNif(username)
			} else {
				user = UserDNI.findByUserOpenID(username)
			}
			if (!user) { 
				throw new UsernameNotFoundException('User not found', username) 
        	} 
			log.debug "@@@@@@@@@@@@@@ - user: " + user
			log.debug "@@@@@@@@@@@@@@ - user.userOpenID: " + user.userOpenID
			log.debug "@@@@@@@@@@@@@@ - user.getAuthorities: " + user.getAuthorities()
			log.debug "@@@@@@@@@@@@@@ - user.getId(): " + user.getId()
			user.getAuthorities().each { authority -> authorities.add(new GrantedAuthorityImpl(authority.authority))}
			//OpenIdUserDetails userDetails = new OpenIdUserDetails(authorities, user.getPassword(), 
			//		user.getUserOpenID(), user.isAccountNonExpired(), user.isAccountNonLocked(), 
			//		user.isCredentialsNonExpired(), user.isEnabled());
			
			//return userDetails;
			//return user;
		}
		OpenIdUser openIdUser = new OpenIdUser(user.getUserOpenID(), user.getPassword(), true, 
				true, true, true, authorities, user.getId()) 
		//openIdUser.transactionAmount = 123
		return  openIdUser
	}		 

}
